package com.xiaominge.utils.pdf;

import com.xiaominge.exception.ParameterRuntimeException;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: system_platform
 * @description: pdf合并工具
 * @author: xiaominge
 * @create: 2021-01-11 17:27
 **/

public class PdfMergeUtils {

    private static PdfMergeUtils pdfMergeUtils;

    public static PdfMergeUtils getUtils() {
        if (pdfMergeUtils == null) {
            synchronized (PdfMergeUtils.class) {
                if (pdfMergeUtils == null) {
                    pdfMergeUtils = new PdfMergeUtils();
                }
            }
        }
        return pdfMergeUtils;
    }

    public static void main(String[] args) throws IOException {
        File dir = new File("D:/桌面/dir.pdf");

        File file1 = new File("D:/桌面/file.pdf");
        File file2 = new File("D:/桌面/file.pdf");

        List<File> files = new ArrayList<>();
        files.add(dir);
        files.add(file1);
        files.add(file2);
        File file = getUtils().PDFMerge(files, "D:/桌面/pdfMergeBox.pdf");
        System.out.println(file);
    }


    public File PDFMerge(List<File> files, String targetPath) throws IOException {
        File file = new File(targetPath);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        this.PDFMerge(files, fileOutputStream);
        return file;
    }

    public void PDFMerge(List<File> files, OutputStream outputStream) throws IOException {
        if (files == null || files.isEmpty()) {
            ParameterRuntimeException.throwException("pdf 文件集合不能为空");
        }
        // pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if (f.exists() && f.isFile()) {
                // 循环添加要合并的pdf
                mergePdf.addSource(f);
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationStream(outputStream);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    }


}
